#pragma once
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <netinet/in.h>
#include <cstring>
#include <unordered_map>
#include "InetAddr.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <fstream>
#include <iostream>

// dictionary.txt
const std::string sep = ": ";
class Dict
{
public:
    Dict(const std::string &path) : _dict_path(path)
    {
    }
    bool LoadDict()
    {
        // 首先要先打开文件
        std::ifstream in(_dict_path);
        if (!in.is_open())
        {
            perror("open fail");
            return false;
        }
        // 说明打开文件成功
        // 读取文件里面的内容并且做好相应的映射
        std::string line;
        std::cout << "我到这里了" << std::endl;
        while (std::getline(in, line))
        {
            auto pos = line.find(sep);
            if (pos == std::string::npos)
                
            {
                std::cout<<"fail"<<std::endl;
                continue;
            }
            std::string english = line.substr(0, pos);
            std::string chinese = line.substr(pos + sep.size());
            if (english.empty() || chinese.empty())
            {
                std::cout << "没有有效内容: " << line << std::endl;
                continue;
            }

            std::cout << "我看的见这里吗" << std::endl;
            _dict.insert(std::make_pair(english, chinese));
            std::cout << "加载 成功" << std::endl;
        }
        return 1;
    }
    std::string Translate(const std::string &word, InetAddr &client)
    {
        auto iter = _dict.find(word);
        if (iter == _dict.end())
        {
            std::cout << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word << "->None"<<std::endl;
            return "None";
        }
        std::cout << "进入到了翻译模块, [" << client.Ip() << " : " << client.Port() << "]# " << word << "->" << iter->second<<std::endl;
        return iter->second;
    }
  
    ~Dict()
    {
    }


    std::string _dict_path; // 路径+文件名
    std::unordered_map<std::string, std::string> _dict;
};
